import 'package:built_collection/built_collection.dart';
import 'package:backend.core/core/domain/entities/api/web/api_web_purchased_subscription_status.dart';
import 'package:backend.core/core/domain/entities/api/web/api_web_purchased_subscription_transaction.dart';

abstract class CreateApiWebPurchasedSubscriptionStatusFromTransactions {
  ApiWebPurchasedSubscriptionStatus call({
    required BuiltList<ApiWebPurchasedSubscriptionTransaction> transactions,
  });
}

class CreateApiWebPurchasedSubscriptionStatusFromTransactionsImpl
    implements CreateApiWebPurchasedSubscriptionStatusFromTransactions {
  const CreateApiWebPurchasedSubscriptionStatusFromTransactionsImpl();

  @override
  ApiWebPurchasedSubscriptionStatus call({
    required BuiltList<ApiWebPurchasedSubscriptionTransaction> transactions,
  }) {
    final unrevokedTransactions = transactions.where((transaction) {
      return !transaction.revoked;
    });

    ApiWebPurchasedSubscriptionTransaction? lastUnrevokedTransaction;

    if (unrevokedTransactions.isNotEmpty) {
      lastUnrevokedTransaction = unrevokedTransactions.last;
    }

    final currentTime = DateTime.now().toUtc();

    if (lastUnrevokedTransaction == null) {
      return ApiWebPurchasedSubscriptionStatus.revoked;
    } else if (lastUnrevokedTransaction.expirationTime.isBefore(currentTime)) {
      return ApiWebPurchasedSubscriptionStatus.expired;
    } else {
      return ApiWebPurchasedSubscriptionStatus.active;
    }
  }
}
